﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BacteriaSimulation.Simulation
{
    public class ApplyForceFieldTask : AbstractTask
    {
        public override TaskOutcome executeTask(Simulation simulation, Bacterium bacterium, SimulationEnvironment env)
        {
            ForceField field = env.ActiveForceField;
            if (field == null)
            {
                return new TaskOutcome(TaskOutcomeType.CONTINUE);
            }

            Vector2D fieldAcceleration = GetForceFieldAcceleration(field, bacterium);
            double shiftX = 0.5 * fieldAcceleration.XComponent * env.SimulationStepInterval * env.SimulationStepInterval;
            double shiftY = 0.5 * fieldAcceleration.YComponent * env.SimulationStepInterval * env.SimulationStepInterval;

            bacterium.Position.X += shiftX;
            bacterium.Position.Y += shiftY;

            return new TaskOutcome(TaskOutcomeType.CONTINUE);
        }

        private Vector2D GetForceFieldAcceleration(ForceField forceField, Bacterium bacterium)
        {
            Vector2D forceVector = forceField.GetAppliedField(bacterium.Position);
            if (forceVector.XComponent == 0 && forceVector.YComponent == 0)
            {
                return new Vector2D(0, 0);
            }
            double forceMagnitude = forceVector.GetMagnitude();
            // Assuming mass == Energy an applying F = m*a
            double accelerationMagnitude = forceMagnitude / bacterium.Energy;
            UnitVector2D forceDirection = new UnitVector2D(forceVector.XComponent, forceVector.YComponent);
            Vector2D accelerationVector = new Vector2D(accelerationMagnitude * forceDirection.XComponent, accelerationMagnitude * forceDirection.YComponent);
            return accelerationVector;
        }
    }
}
